package com.ysh.xiaomi.dao.impl;

import com.ysh.xiaomi.dao.AddressDao;
import com.ysh.xiaomi.pojo.TbAddress;
import com.ysh.xiaomi.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 袁胜虎 on 2022/8/18 19:41
 */
public class AddressDaoImpl implements AddressDao {
    @Override
    public List<TbAddress> findAllAddressByUserId(Long userId) {
        QueryRunner qr = new QueryRunner();
        String sql = "select * from tb_address where uid = ?";
        try {
            List<TbAddress> addressList = qr.query(DbUtils.getConn(), sql, new BeanListHandler<>(TbAddress.class), userId);
            return  addressList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public TbAddress findById(Long addressId) {
        QueryRunner qr = new QueryRunner();
        String sql="select * from tb_address where id = ?";
        try {
            TbAddress address = qr.query(DbUtils.getConn(), sql, new BeanHandler<>(TbAddress.class), addressId);
            return address;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int insertAddress(TbAddress address) {
        QueryRunner qr = new QueryRunner();
        String sql ="insert into tb_address values(null,?,?,?,?,'0')";
        try {
            int update = qr.update(DbUtils.getConn(), sql, address.getDetail(), address.getName(), address.getPhone(), address.getUid());
            return update;

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void deleteAddressByAid(String aid) {
        QueryRunner qr = new QueryRunner();
        String sql = "delete from tb_address where id = ?";
        try {
            qr.update(DbUtils.getConn(),sql,aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
